package com.dhh.sky.activity;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.Window;
import android.widget.ArrayAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.devspark.appmsg.AppMsg;
import com.dhh.sky.R;
import com.dhh.sky.service.BaseService;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.util.OperationManager;
import com.dhh.sky.widget.SlideMenuFragment;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public abstract class BasicActivity extends SlidingFragmentActivity implements ActionBar.OnNavigationListener {
	protected IntentFilter syncFilter = new IntentFilter(Constant.SERVICE_SYNC_REFRESH);
	protected IntentFilter conFilter = new IntentFilter(Constant.SERVICE_NAME_CONNECT);
	protected IntentFilter operationFilter = new IntentFilter(Constant.SERVICE_NAME_BASIC);
	protected IntentFilter progressFilter = new IntentFilter(Constant.SERVICE_NAME_OPEN);
	protected SyncReceiver syncReceiver = new SyncReceiver();	
	protected OperationReceiver opReceiver = new OperationReceiver();
	protected ConReceiver conReceiver = new ConReceiver();
	protected ProgressReceiver progressReceiver = new ProgressReceiver();
	protected MenuItem refreshAction;
	protected OperationManager om;
	protected String currentPath = Constant.SKYFRIVE_PATH_HOME;
	protected FileManager fm;
	
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setBehindContentView(R.layout.menu_frame);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		
        getSupportFragmentManager().
			beginTransaction().
			replace(R.id.menu_frame, new SlideMenuFragment()).
			commit();		
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		//sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		
		om = new OperationManager(this);
		fm = new FileManager(this);
	}
	
	@Override
	public void onStart(){
		super.onStart();
		initActionBar();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		registerReceiver(syncReceiver, syncFilter);
		registerReceiver(opReceiver, operationFilter);	
		registerReceiver(conReceiver, conFilter);		
		registerReceiver(progressReceiver, progressFilter);		
		refreshSyncStatus();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(syncReceiver);
		unregisterReceiver(opReceiver);
		unregisterReceiver(conReceiver);
		unregisterReceiver(progressReceiver);
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
	        case android.R.id.home:     
	        	toggle();
				return true;
        }
    	
        return false;
    }
	
	protected void initActionBar(){
    	getSupportActionBar().setHomeButtonEnabled(true);    
    	getSupportActionBar().setIcon(R.drawable.ic_app_menu);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);   
        setSupportProgressBarIndeterminateVisibility(true);
	}
	
	public void initListNavigation(){
		Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.views, R.layout.sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, this);
	}	
	
	abstract void refresh();
	
	protected void handleException(){
		
	}
	
	public void showToast(String message,boolean isAlert){
		 AppMsg.Style style = AppMsg.STYLE_INFO;
		 if(isAlert){
			 style = AppMsg.STYLE_ALERT;
		 }
		AppMsg appMsg = AppMsg.makeText(this, message, style);
		appMsg.setLayoutGravity(Gravity.BOTTOM);
		appMsg.show();
	}
	
	protected boolean refreshSyncStatus(){
		boolean flag = false;		
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);	    
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (BaseService.class.getName().equals(service.service.getClassName())) {
	        	flag = true;
	        	break;
	        }
	    }
        setSupportProgressBarIndeterminateVisibility(flag);
	    
	    return flag;
	}
	
	protected class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(!intent.getExtras().getBoolean(Constant.SYNC_PARAM_ERROR)){
				refresh();
				showToast("Synchronize successfully!",false);
			}else{
				showToast("Fail to synchronize!",true);
			}
			
			onProgressStatus(false);
		}
	}
	
	protected class OperationReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {	
			String path = intent.getExtras().getString(Constant.SERVICE_PARAM_ID);
			boolean isDone = intent.getExtras().getBoolean(Constant.SERVICE_PARAM_DONE);
			if(!isDone){
				showToast(intent.getExtras().getString(Constant.SERVICE_PARAM_MSG),true);
			}
			
			if(path.equals(currentPath)){
				refresh();				
			}			
			onProgressStatus(false);
		}
	}
	
	protected class ConReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {	
			showToast(intent.getExtras().getString(Constant.SERVICE_PARAM_MSG),true);		
			onProgressStatus(false);
		}
	}
	
	protected class ProgressReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {	
			String path = intent.getExtras().getString(Constant.PARAM_PATH);
			String id = intent.getExtras().getString(Constant.PARAM_ID);
			int progress = intent.getExtras().getInt(Constant.PARAM_PROGRESS);
			boolean isSucc = intent.getExtras().getBoolean(Constant.PARAM_DONE);
			updateItemProgress(isSucc,id,path,progress);
			
			onProgressStatus(false);
		}
	}
	
	protected abstract void updateItemProgress(boolean isSucc,String path,String id,int progress);
    
    public void onProgressStatus(boolean isProgress){
    	Message msg = new Message();
    	Bundle data = new Bundle();
    	data.putBoolean(Constant.PARAM_DONE, isProgress);
    	msg.setData(data);
    	progressHandler.sendMessage(msg);
    	
    }
	
	public String getCurrentPath(){
		return this.currentPath;
	}
	

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
    
    protected Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		String text = msg.getData().getString(Constant.PARAM_MESSAGE);
    		showToast(text,true);
        }
    };
    
    Handler progressHandler = new Handler() {
        public void handleMessage(Message msg) {
        	boolean isProgress = msg.getData().getBoolean(Constant.PARAM_DONE);        	
        	if(isProgress){
        		if(refreshAction!=null){
        			refreshAction.setActionView(R.layout.progress_view);
        		}
        	}else{
        		if(refreshAction!=null)
        			refreshAction.setActionView(null);
        	}
        }
    };
    
    public void sendToast(String message){
    	Bundle data = new Bundle();
		data.putString(Constant.PARAM_MESSAGE, message);
		Message msg = new Message();
		msg.setData(data);
		msgHandler.sendMessage(msg);
    }
    
    public void slideMenuToggle(){
    	this.toggle();
    }

}
